package com.youlai.system.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youlai.system.common.result.PageResult;
import com.youlai.system.common.result.Result;
import com.youlai.system.model.query.ExamPageQuery;
import com.youlai.system.model.vo.ExamDetailVO;
import com.youlai.system.model.vo.ExamExportVO;
import com.youlai.system.model.vo.ExamPageVO;
import com.youlai.system.security.util.SecurityUtils;
import com.youlai.system.service.SysExamService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 考试名单控制器
 */
@Tag(name = "20.考试名单接口")
@RestController
@RequestMapping("/api/v1/exams")
@RequiredArgsConstructor
public class SysExamController {

    private final SysExamService examService;

    @Operation(summary = "考试名单分页列表")
    @GetMapping("/page")
    public PageResult<ExamPageVO> getScorePage(@ParameterObject ExamPageQuery queryParams) {
        if (SecurityUtils.isStudent()) {
            queryParams.setLoginUserId(SecurityUtils.getUserId());
        }
        IPage<ExamPageVO> result = examService.getExamPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "获取生成考试名单的详细依赖等级与成绩数据")
    @GetMapping("/{examId}/getExamDetailList")
    public Result<List<ExamDetailVO>> getExamDetailList(@Parameter(description = "考试名单ID") @PathVariable Long examId) {
        List<ExamDetailVO> examDetailVOList = examService.getExamDetailList(examId);
        return Result.success(examDetailVOList);
    }

    @Operation(summary = "导出考试名单")
    @GetMapping("/_export")
    public void exportUsers(ExamPageQuery queryParams, HttpServletResponse response) throws IOException {
        String fileName = "考试名单列表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        List<ExamExportVO> examExportVOList = examService.listExportExams(queryParams);
        EasyExcel.write(response.getOutputStream(), ExamExportVO.class).sheet("考试名单列表")
                .doWrite(examExportVOList);
    }
}
